<template>
  <div>
    <h2>用户登录</h2>
    <el-form class="loginForm"
             :model="loginForm"
             :rules="rules"
    >
      <el-form-item prop="username">
        <el-input type="text" v-model="loginForm.username"  style="width: 220px" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password"  v-model="loginForm.password" style="width: 220px" placeholder="请输入密码"></el-input>
      </el-form-item>

      <el-form-item prop="code">
        <el-input type="text"  v-model="loginForm.code" style="width: 220px" placeholder="请输入验证码"></el-input>
        <el-image :src="captchaImg" class="captchaImg" title="看不清，换一张" @click="getCaptchaImg"></el-image>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {ElMessage} from "element-plus";
import {getCaptcha, login} from "../api/user.ts";
import {useRouter} from "vue-router";
const $router = useRouter();
const captchaImg = ref('')
const loginForm = ref({
  username: '',
  password: '',
  code: ''
})

// 获取验证码
const getCaptchaImg = () => {
    getCaptcha().then(res => {
        captchaImg.value = res.data;
    })
}
//登录
const handlerLogin = () => {

  login(loginForm.value).then(res => {
       if(res.data.flag) {
          //保存用户信息
         localStorage.setItem("token",res.data.data.token);
         localStorage.setItem("user",JSON.stringify(res.data.data));
          //跳转到首页
          $router.push({path:'/index'})

       }else{
          ElMessage.error(res.data.message);
       }
  })

}
getCaptchaImg();
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ]
}
</script>

<style scoped>
.loginForm{
  border-radius: 15px;
  background-clip: padding-box;
  margin: 100px auto;
  width: 350px;
  padding: 35px 15px 35px 15px;
  border: 1px solid #eaeaea;
  background: #ffffff;
  box-shadow: 0 0 25px #caeaea;
}
.captchaImg {
  float: right;
  margin-left: 8px;
  border-radius: 4px;
}
</style>